#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <stdlib.h>
#include <pthread.h>

#define CNT     5

static int job;
static pthread_mutex_t job_mut = PTHREAD_MUTEX_INITIALIZER;

static pthread_cond_t cond = PTHREAD_COND_INITIALIZER;

static void *thr_job(void *arg);

int main(void)
{
    pthread_t tid[CNT];
    int err, i;

    for (i = 0; i < CNT; i++) {
        err = pthread_create(tid + i, NULL, thr_job, NULL);
        if (err) {
            fprintf(stderr, "pthread_create():%s", strerror(err));
            return 1;
        }
    }

    alarm(5);

    while (1) {
        pthread_mutex_lock(&job_mut);

        while (job >= 0) 
            pthread_cond_wait(&cond, &job_mut);

        sleep(1);
        write(1, " ", 1);
        job = 0; // 一轮打印完毕,重新开始一轮
        pthread_cond_signal(&cond);
        pthread_mutex_unlock(&job_mut);
    }

    for (i = 0; i < CNT; i++)
        pthread_join(tid[i], NULL);

    pthread_mutex_destroy(&job_mut);

    return 0;
}


static void *thr_job(void *arg)
{
    while (1) {
        pthread_mutex_lock(&job_mut);

        while (-1 == job) 
            pthread_cond_wait(&cond, &job_mut);    

        switch (job) {
            case 0:
                write(1, "a", 1);
                break;
            case 1:
                write(1, "b", 1);
                break;
            case 2:
                write(1, "c", 1);
                break;
            case 3:
                write(1, "d", 1);
                break;
            case 4:
                write(1, "e", 1);
                break;
            default:
                break;
        }

        job++;
        if (5 == job)
            job = -1;
        pthread_cond_broadcast(&cond);
        pthread_mutex_unlock(&job_mut);
    }

    return (void *)0;
}

